package com.aspire.boc.mms.wmf.filter;

import java.util.HashSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.aspire.boc.mms.wmf.constants.GlobalConstant;
import com.aspire.boc.mms.wmf.log.OperLogger;
import com.aspire.boc.mms.wmf.model.SecurityUser;
import com.aspire.boc.mms.wmf.util.AuthAnnotation.ActionAuth;

public class ActionAuthInterceptor implements HandlerInterceptor {
	@SuppressWarnings("unchecked")
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		ActionAuth actionAuth = handlerMethod.getBeanType().getAnnotation(
				ActionAuth.class);
		if (actionAuth == null) {
			return true;
		}
		HttpSession session = request.getSession();
		SecurityUser securityUser = (SecurityUser) session.getAttribute("securityUser");
		boolean isAdmin = securityUser.isSystemAdmin();
		HashSet<String> userActiondos = (HashSet<String>) session
				.getAttribute(GlobalConstant.WMF_USER_ACTIONDOS);
		String requestDo = request.getServletPath();
		if ((userActiondos != null && userActiondos.contains(requestDo))
				|| isAdmin) {
			return true;
		}
		OperLogger.log(this,
				">>>>>ActionAuthInterceptor validate result: no permissions in request["
						+ requestDo + "](BTW: all user auth action .do: "
						+ userActiondos + ")", OperLogger.LOG_LEVEL.ERROR);
		// 如当前请求为页面访问，形如 /xxx/index.do，则直接返回字符串"权限受限"；否则，返回json串
		String returnMsg = null;
		// "权限受限"
		String errroMsg = "&#x6743;&#x9650;&#x53D7;&#x9650;";
		if (!requestDo.endsWith("/index.do")) {
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("failure", Boolean.TRUE);
			jsonResult.put("msg", errroMsg);
			returnMsg = jsonResult.toString();
		} else {
			returnMsg = errroMsg;
		}
		response.getWriter().write(returnMsg);
		return false;
	}

	/**
	 * 控制器的方法已经执行完毕，转换成视图之前的处理
	 */
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 视图已处理完后执行的方法，通常用于释放资源；
	 */
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
